package com.xcm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.constant.DateFormatConstant;
import com.xcm.constant.OperationLogConstant;
import com.xcm.constant.ResponseConstant;
import com.xcm.exception.ServiceException;
import com.xcm.model.JsonResponse;
import com.xcm.model.TbOperationLog;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.OperationLogService;
import com.xcm.service.ProgramJsonService;
import com.xcm.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 处理公共Controller问题，如修改密码、获取菜单信息、获取用户信息
 */
@Controller
@RequestMapping(value = "/web")
public class WebController {

	private static Logger logger = LoggerFactory.getLogger(WebController.class);
	@Autowired
	private ProgramJsonService programJsonService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private RedisCacheDao redisCacheDao;
	@Autowired
	private CustomProperties customProperties;
	@Autowired
	private OperationLogService operationLogService;
	/**
	 * 跳转至首页
	 */
	@RequestMapping(value = "/goHome")
	public String goHome(Model model) {
		//实时概况
		String currentDate = DateUtils.longTimeStampToStringDate(System.currentTimeMillis(), DateFormatConstant.DATE_SHORT_ISO_CH);
		model.addAttribute("currentDate", currentDate);
		//广告发布数
		Long programJsonCount = programJsonService.getProgramJsonCount();
		model.addAttribute("programJsonCount", programJsonCount);
		//发布异常数（校验失败数+发布失败数<所有终端下载成功才成功>）
		//校验失败数
		Long authFailureCount = programJsonService.getProgramJsonAuthFailureCount();
		//发布失败数
		Long publishFailureCount = programJsonService.getProgramJsonPublishFailureCount();
		model.addAttribute("failureCount", authFailureCount + publishFailureCount);
		//联网终端数
		Long onlineDeviceCount = deviceInfoService.getOnlineDeviceInfoCount();
		model.addAttribute("onlineDeviceCount", onlineDeviceCount);
		//异常终端数
		Long offlineDeviceCount = deviceInfoService.getOfflineDeviceInfoCount();
		model.addAttribute("offlineDeviceCount", offlineDeviceCount);
		return "home";
	}

	/**
	 * 获取菜单数据
	 */
	@ResponseBody
	@RequestMapping(value = "/getMenuDatas", method = RequestMethod.POST)
	public Object getMenuData(HttpServletRequest request) {
		Object attribute = request.getAttribute(customProperties.getCookieName());
		if (attribute != null) {
			String key = DESUtils.decrypt(String.valueOf(attribute), customProperties.getSecretKey());
			Object cache = redisCacheDao.getCache(customProperties.getCookieName(), key);
			if (cache != null) {
				JSONObject jsonObject = JSON.parseObject(String.valueOf(cache));
				if (jsonObject == null) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "登录失效，请重新登录");
				}
				JSONObject xcipsJsonObj = jsonObject.getJSONObject("xcips");
				if (xcipsJsonObj == null) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "登录失效，请重新登录");
				}
				JSONArray menusJSONArray = xcipsJsonObj.getJSONArray("menus");
				return menusJSONArray;
			}
		}
		return new JsonResponse(ResponseConstant.CODE_FAIL, "登录失效，请重新登录");
	}

	/**
	 * 跳转到修改密码界面
	 */
	@RequestMapping(value = "/goUpdatePasswordPage")
	public String goUpdatePasswordPage() {
		return "update_password";
	}

	/**
	 * 修改密码(调用统一登录接口)
	 */
	@ResponseBody
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public Object updatePassword(String password, String newPassword, String confirmedPassword, HttpServletRequest request) {
		if (StringUtils.isBlank(password) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmedPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
		}
		//验证新密码与确认密码是否一致
		if (!newPassword.equals(confirmedPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "两次输入密码不一致");
		}
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("WebController updatePassword 修改密码失败：" + e.getMessage());
			return e.getMessage();
		}
		if (user == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名为空，请联系管理员");
		}
		//加密密钥
		String secretKey = customProperties.getSecretKey();
		//参数Map
		Map<String, Object> params = Maps.newHashMap();
		String userName = user.getString("userName");
		params.put("ticket", request.getAttribute(customProperties.getCookieName()));
		params.put("userName", DESUtils.encrypt(userName,secretKey));
		params.put("password", DESUtils.encrypt(password, secretKey));
		params.put("newPassword", DESUtils.encrypt(newPassword, secretKey));
		String post = RestClientUtils.post(customProperties.getSsoLoginUrl() + "/changePassword", params);
		String msg = "修改密码失败";
		if (StringUtils.isNotBlank(post)) {
			JSONObject jsonObject = JSON.parseObject(post);
			int code = jsonObject.getIntValue(ResponseConstant.RESPONSE_JSON_CODE);
			if (ResponseConstant.CODE_SUCCESS == code) {
				//保存操作日志
				TbOperationLog operationLog = new TbOperationLog();
				operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
				operationLog.setOperationContent("修改密码成功");
				operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
				operationLog.setOperationTime(System.currentTimeMillis());
				//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
				operationLog.setUserName(userName);
				operationLog.setRealName("");
				operationLog.setOperationIp(HttpUtils.getRemortIP(request));
				operationLogService.saveOperationLog(operationLog);
				return new JsonResponse(ResponseConstant.CODE_SUCCESS, "修改密码成功");
			} else {
				msg = jsonObject.getString(ResponseConstant.RESPONSE_JSON_MSG);
			}
		}
		//保存操作日志
		TbOperationLog operationLog = new TbOperationLog();
		operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
		operationLog.setOperationContent("修改密码失败");
		operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
		operationLog.setUserName(userName);
		operationLog.setRealName("");
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
		return new JsonResponse(ResponseConstant.CODE_FAIL, msg);
	}

	/**
	 * 获取用户信息
	 */
	@ResponseBody
	@RequestMapping(value = "/getUser")
	public Object getUser(HttpServletRequest request) {
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("WebController getUser 获取用户信息失败：" + e.getMessage());
			return e.getMessage();
		}
		if (user == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户信息为空，请联系管理员");
		}
		return user;
	}
}
